package com.zzyl.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationPageDto;
import com.zzyl.entity.Reservation;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.TimeCountVo;
import org.apache.ibatis.builder.BuilderException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements ReservationService {

    @Override
    public Integer getCancelledCount() {
        DateTime begin = DateUtil.beginOfDay(new Date());//今天开始时间
        DateTime end = DateUtil.endOfDay(new Date());//今天结束时间
        Long userId = UserThreadLocal.getUserId();//当前用户id

        //查询指定时间段内,当前用户的取消次数
        return getBaseMapper().getCancelledCount(begin, end, userId);
    }

    @Override
    public List<TimeCountVo> getRemainingCount(Long time) {
        LocalDateTime begin = LocalDateTimeUtil.of(time);//开始时间
        LocalDateTime end = begin.plusHours(24);//结束时间
        return getBaseMapper().getRemainingCount(begin, end);
    }

    @Override
    public void saveReservation(Reservation reservation) {
        //取消次数大于3次的也不能预约
        int cancelledReservationCount = getCancelledCount();
        if (cancelledReservationCount >= 3) {
            throw new BuilderException("今天取消次数已达上限，不可进行预约");
        }

        reservation.setStatus(0);//设置状态:待报到

        try {
            getBaseMapper().insert(reservation);
        } catch (Exception e) {
            throw new BuilderException("此手机号已预约该时间");
        }
    }

    @Override
    public PageResponse<Reservation> findByPage(ReservationPageDto dto) {
        //设置分页条件
        Page<Reservation> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        //设置业务条件
        LambdaQueryWrapper<Reservation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dto.getStatus() != null, Reservation::getStatus,dto.getStatus())
                .eq(Reservation::getCreateBy,UserThreadLocal.getUserId());

        //查询
        page = getBaseMapper().selectPage(page,wrapper);

        return new PageResponse(page);
    }
}
